<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card>
      <el-form :model="form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="文件名" porp="fileName">
              <el-input v-model="form.fileName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="文件类型" porp="fileType">
              <el-select v-model="form.fileType" placeholder="请选择">
                <el-option v-for="item in fileTypeOptions" :key="item.id" :label="item.name"
                  :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="文件状态" porp="fileStatus">
              <el-select v-model="form.status" placeholder="请选择">
                <el-option label="全部" value=""></el-option>
                <el-option label="未删除" value="0"></el-option>
                <el-option label="已删除" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="mt-2">
          <el-col :span="8">
            <el-form-item label="统计时间段：" porp="createTime">
              <el-date-picker v-model="form.createTime" @change="datetimeChange" type="datetimerange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card style="margin-top: 20px;">
      <div class="" style="display: flex; justify-content: space-between; margin-bottom: 20px;">
        <div>
          <!-- <el-button type="danger" :disabled="!multipleSelection" plain @click="handleBulkDelete">批量删除</el-button>
          <el-button type="primary" plain @click="handleReset">批量操作</el-button> -->
        </div>
        <el-button type="primary" @click="uploadVisible = true">上传文档</el-button>
      </div>
      <!-- 文件列表 -->
      <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" align="center" width="55"></el-table-column>
        <el-table-column prop="fileId" label="文件ID" align="center" width="100"></el-table-column>
        <el-table-column prop="originalFileName" label="文件名称" align="center">
          <template #default="scope">
            <el-link type="primary" @click="checkFile(scope.row)">{{ scope.row.originalFileName }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="fileSize" label="文件大小" align="center"></el-table-column>
        <!-- 添加文件名称，如果是图片回显 -->
        <el-table-column prop="fileId" label="图片" align="center">
          <template #default="{ row }">
            <el-image v-if="row.fileType == '图片'" style="width: 30px; height: 30px" :src="getImageUrl(row.filePath)"
              :preview-src-list="[getImageUrl(row.filePath)]" fit="cover" preview-teleported>
              <template #error>
                <div class="image-slot">
                  <el-icon>
                    <Picture />
                  </el-icon>
                </div>
              </template>
            </el-image>
            <div v-else></div>
          </template>
        </el-table-column>
        <el-table-column prop="fileType" label="文件类型" align="center"></el-table-column>
        <el-table-column prop="createTime" label="上传时间" align="center" width="200"></el-table-column>
        <el-table-column prop="updater" label="上传用户" align="center" width="100"></el-table-column>
        <el-table-column prop="status" label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status == '0'" type="success">正常</el-tag>
            <el-tag v-if="scope.row.status == '1'" type="info">禁用</el-tag>
            <el-tag v-if="scope.row.status == '2'" type="danger">删除</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <!-- <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button> -->
            <el-button v-if="scope.row.status != '2'" type="text" size="small"
              @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px;">
        <el-pagination v-model:current-page="form.pageNum" v-model:page-size="form.pageSize"
          :page-sizes="[10, 20, 30, 40]" background layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 上传文件弹窗 -->
    <el-dialog v-model="uploadVisible" align-center title="上传文档" width="600">
      <el-form ref="formRef" :model="uploadForm" label-width="80px">
        <el-form-item label="选择文件">
          <uploadFile ref="childRef" @success="uploadSuccess" accept="*" />
        </el-form-item>
        <el-form-item label="文件描述">
          <el-input v-model="uploadForm.description" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="uploadVisible = false">取消</el-button>
          <el-button type="primary" @click="uploadSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看文件信息 -->
    <el-dialog v-model="fileMessageVisible" align-center title="文件信息" width="1000">
      <el-descriptions title="" style="margin-left: 20px;margin-top: 20px;">
        <el-descriptions-item label="文件描述">{{ fileMessageDateilForm.description }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ fileMessageDateilForm.creator }}</el-descriptions-item>
        <el-descriptions-item label="最后更新人">{{ fileMessageDateilForm.updater }}</el-descriptions-item>
        <el-descriptions-item label="文件路径">
          <span style="margin-right: 10px;">{{ fileMessageDateilForm.filePath.slice(0, 5) }}...</span>
          <el-link type="primary" @click="copyFile">复制</el-link>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ fileMessageDateilForm.createTime }}
        </el-descriptions-item>
        <el-descriptions-item label="最后更新时间">
          {{ fileMessageDateilForm.uploadTime }}
        </el-descriptions-item>
      </el-descriptions>
      <el-divider />
      <div style="margin-left: 20px;">
        <div>项目需求说明：</div>
        <p style="margin-left: 20px;"></p>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="fileMessageVisible = false">取消</el-button>
          <el-button @click="clickDownloadFile" type="primary">下载</el-button>
          <el-button type="primary" @click="handleDelete(fileMessageDateilForm)">
            删除
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { ElMessageBox } from 'element-plus';
import { listFileManage, delFileManage, getFileTypeSelect, addFileManage, getFileManage } from '@/api/sysManage/fileManage';
import uploadFile from '@/components/UploadFile/index.vue';

const childRef = ref(null)

const { proxy } = getCurrentInstance();
const uploadVisible = ref(false);
// watch(() => uploadVisible.value,
//   (newVal) => {
//     // 当弹窗从显示变为隐藏时（newVal为false），执行重置
//     if (!newVal) {
//       resetForm();
//     }
//   }
// );
const resetuploadForm = () => {
  uploadForm.value = {
    fileIds: [],
    description: ''
  }
}
const getImageUrl = (pipeImage) => {
  if (!pipeImage) return null;
  return import.meta.env.VITE_APP_IMAGE_URL + pipeImage;
}
// 定义表单引用
const formRef = ref(null);
// 定义搜索表单数据模型
const form = ref({
  fileName: '',
  fileType: '',
  status: '',
  pageNum: 1,
  pageSize: 10,
  startTime: '',
  endTime: '',
  createTime: ''
});
const fileMessageDateilForm = ref({});
const fileTypeOptions = ref([]);
const fileMessageVisible = ref(false);
const uploadForm = ref({
  fileIds: [],
  description: ''
});

const multipleSelection = ref('');
// 定义表格数据
const tableData = ref([]);

// 分页配置
const total = ref(0);
// 处理搜索
function handleSearch() {
  listFileManage(form.value).then((response) => {
    total.value = response.total;
    tableData.value = response.rows;
  });
}



// 处理重置
function handleReset() {
  form.value = {
    fileName: '',
    fileType: '',
    fileStatus: '',
    pageNum: 1,
    pageSize: 10,
    startTime: '',
    endTime: '',
    createTime: ''
  };
}
const handleSizeChange = (size) => {
  form.value.pageSize = size;
  handleSearch();
};
const handleCurrentChange = (page) => {
  form.value.pageNum = page;
  handleSearch();
};
// 处理编辑
function handleEdit(index, row) {
  console.log('Edit:', index, row);
}

// 处理删除
function handleDelete(row) {
  ElMessageBox.confirm('此操作将永久删除, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    delFileManage(row.fileId).then(() => {
      handleSearch();
      fileMessageVisible.value = false;
    })
  })

}

// 时间选择器
const datetimeChange = (value) => {
  console.log(value);

  form.value.startTime = value[0];
  form.value.endTime = value[1];
};


// 批量选择
const handleSelectionChange = (val) => {
  multipleSelection.value = val.map((item) => item.fileId).join(',');
}


// 批量删除
const handleBulkDelete = () => {
  if (!multipleSelection.value) {
    return
  };
  ElMessageBox.confirm('此操作将永久删除, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    delFileManage(multipleSelection.value).then(() => {
      handleSearch();
    })
  })
}

// 提交表单
function uploadSubmit() {
  addFileManage(uploadForm.value).then(() => {
    childRef.value?.clearFileList()
    resetuploadForm();
    handleSearch();
    uploadVisible.value = false;
  })
}
// 查看文件
const checkFile = (row) => {
  getFileManage(row.fileId).then((response) => {
    console.log(response);

    fileMessageDateilForm.value = response.data;
    fileMessageVisible.value = true;
  })
}
const copyFile = () => {
  navigator.clipboard.writeText(import.meta.env.VITE_APP_UPLOAD_URL + fileMessageDateilForm.value.filePath).then(() => {
    ElMessage.success('复制成功');
  })
}
const clickDownloadFile = () => {
  proxy.download('/basic/file_manage/download/' + fileMessageDateilForm.value.fileId, {}, `${fileMessageDateilForm.value.originalFileName}.png`);
  fileMessageVisible.value = false;
}


const uploadSuccess = (fileIds) => {
  uploadForm.value.fileIds = fileIds;
}

getFileTypeSelect().then((response) => {
  console.log(response);

  fileTypeOptions.value = response.data;
})

handleSearch();
</script>

<style scoped>
.el-card :deep(.el-form-item) {
  margin-bottom: 0px;
}
</style>